/**
 * AbstractDateTimeAttributeRenderer.java
 *
 * Copyright 2010 Jack Leow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package my.edu.clhs.stringtemplate.renderer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.antlr.stringtemplate.AttributeRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Abstract super class for date/time attribute renderers. There will be a
 * concrete subclass for specific date/time implementations (e.g.,
 * {@link java.util.Date}, {@link java.util.Calendar},
 * {@link org.joda.time.base.AbstractInstant}).
 *
 * @author Jack Leow
 * @version 1.0
 * @since 1.0 (Dec 26, 2010, 5:36 AM)
 */
abstract class AbstractDateTimeAttributeRenderer
        implements AttributeRenderer {
    private static final Logger log =
        LoggerFactory.getLogger(AbstractDateTimeAttributeRenderer.class);
    
    /**
     * Cache for date formatters. This is {@link ThreadLocal} as
     * {@link SimpleDateFormat}s are not thread-safe per its API documentation.
     */
    private static final ThreadLocal FORMATTER_CACHE = new ThreadLocal() {
        protected Object initialValue() {
            return new HashMap();
        }
    };
    
    private SimpleDateFormat getFormatter(String format) {
        Map formatterCache = (Map)FORMATTER_CACHE.get();
        SimpleDateFormat formatter =
            (SimpleDateFormat)formatterCache.get(format);
        if (formatter == null) {
            formatter = new SimpleDateFormat(format);
            formatterCache.put(format, formatter);
        }
        
        return formatter;
    }
    
    /**
     * This does the actual work of converting the {@link Date} to a string.
     * If a format is provided, it will be used to format the date, otherwise
     * the full ISO8601 (<tt>"yyyyMMdd'T'HHmmss.SSSZ"</tt>) format is used.
     * 
     * @param date the date to format.
     * @param format the date format to use (can be <tt>null</tt>).
     * @return the string representation of the date.
     */
    final String toStringInternal(Date date, String format) {
        log.debug("entering toStringInternal(Object,String)");
        String str;
        
        if (date != null) {
            if (format == null) format = "yyyyMMdd'T'HHmmss.SSSZ";
            str = getFormatter(format).format(date);
        } else {
            str = null;
        }
        
        log.debug("exiting toStringInternal(Object,String)");
    	return str;
    }
    
    /**
     * Sub-classes must implement this to convert dates/times represented by the
     * classes they support (e.g., {@link java.util.Calendar},
     * {@link org.joda.time.base.AbstractInstant} etc) to a {@link Date} of the
     * same date/time.
     * 
     * @param o Object that represent a date/time.
     *  Guaranteed to never be <tt>null</tt>.
     * @return {@link Date} representing the same date/time.
     */
    abstract Date toDate(Object o);
    
    public final String toString(Object o, String format) {
        log.debug("entering toString(Object,String)");
        log.debug("exiting toString(Object,String)");
        return o != null ? toStringInternal(toDate(o), format) : null;
    }
    
    /**
     * Delegates to {@link #toString(Object,String)} with a <tt>null</tt>
     * formatName.
     */
    public final String toString(Object o) {
        log.debug("entering toString(Object)");
        log.debug("exiting toString(Object)");
        return toString(o, null);
    }
}